package com.lwj.service.system;

import com.lwj.dto.system.MenuDto;
import com.lwj.mapper.system.MenuMapper;
import com.lwj.model.system.Menu;
import com.lwj.service.DozerService;
import com.lwj.service.SpringUtil;
import com.lwj.service.configuration.PermissionService;
import com.lwj.utils.CollectionTool;
import com.lwj.vo.system.MenuVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class MenuServiceImpl  implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private DozerService dozerService;
    @Autowired
    private PermissionService permissionService;

    @Override
    public int deleteByPrimaryKey(String menuId) {
        return 0;
    }

    @Override
    public int insert(Menu record) {
        return 0;
    }

    @Override
    public int insertSelective(Menu record) {
        return 0;
    }

    @Override
    public Menu selectByPrimaryKey(String menuId) {
        return null;
    }

    @Override
    public int updateByPrimaryKeySelective(Menu record) {
        return 0;
    }

    @Override
    public int updateByPrimaryKey(Menu record) {
        return 0;
    }

    @Override
    public List<MenuVo> menuTree(String type) {
        List<MenuVo> menuVos = menuMapper.listMenu(type,null,null);
        return CollectionTool.buildTree(menuVos);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String save(MenuDto menuDto) {
        Menu menu = dozerService.map(menuDto, Menu.class);
        if(StringUtils.hasText(menu.getMenuId())){
            menu.setParentId(null);
            menuMapper.updateByPrimaryKeySelective(menu);
        }else {
            menu.setStatus("0");
            menu.setUseRole("0");
            menuMapper.insertSelective(menu);
            permissionService.initAdminPermission(menu.getMenuId());
        }
        return menu.getMenuId();
    }


    @Override
    public List<MenuVo> userMenu( String departmentRoleId) {
        //不需要角色的菜单
        List<MenuVo> menuVos = menuMapper.listMenu("0","1","0");
        //角色有的菜单
        if(StringUtils.hasText(departmentRoleId)){
            List<MenuVo> menuVos2 = menuMapper.userRoleMenu(SpringUtil.getUserId(),"");
            menuVos.addAll(menuVos2);
        }
        return CollectionTool.buildTree(menuVos);
    }

    @Override
    public void changeStatus(MenuDto menuDto) {
        List<String> childrenIds = childrenIds(menuDto.getMenuId());
        menuMapper.changeStatus(childrenIds,menuDto.getStatus());
    }
    private List<String> childrenIds(String menuId){
        String s = menuMapper.childrenIds(menuId);
        List<String> childrenIds = CollectionTool.strToList(s);
        childrenIds.remove("$");
        return childrenIds;
    }


}
